package com.cy.cy2025.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Paint
import android.graphics.Rect
import android.os.Bundle
import android.os.Handler
import android.view.View
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
import androidx.compose.ui.graphics.nativeCanvas
import androidx.compose.ui.layout.LastBaseline
import androidx.compose.ui.layout.layout
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.Dimension
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import coil3.compose.AsyncImage
import com.cy.cy2025.R
import com.cy.cy2025.util.LogUtil
import com.cy.cy2025.util.ToastUtil

class ComposeTestActivity : AppCompatActivity() {


    companion object {
        const val TAG = "ComposeTestActivity"
    }

    val vm by lazy { ViewModelProvider(this)[ComposeTestVm::class.java] }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        val v : View = findViewById(android.R.id.content)
        setContent {

            //ContentV()
            //ComposeTest1()
            //Text(text = "Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!",modifier = Modifier.noFontPadding().background(Color.Cyan))
            //CustomDrawExample()
            ComposeTest1()
        }

        //vm.initData()

    }


    /**
     * 使用画布示例
     */
    @Composable
    fun CustomDrawExample() {
        Canvas(
            modifier = Modifier.size(200.dp) // 定义绘制区域大小
        ) {
            // 1. 绘制背景圆形
            drawCircle(
                color = Color.LightGray,
                radius = size.minDimension / 2,
                center = Offset(size.width / 2, size.height / 2)
            )

            // 2. 绘制边框
            drawCircle(
                color = Color.Blue,
                radius = size.minDimension / 2 - 2.dp.toPx(),
                center = Offset(size.width / 2, size.height / 2),
                style = Stroke(width = 4.dp.toPx())
            )

            // 3. 绘制文本（通过 nativeCanvas 调用原生绘制文本 API）
            drawIntoCanvas { canvas ->
                val text = "Custom Draw\nExample"
                val textPaint = Paint().apply {
                    color = android.graphics.Color.BLACK
                    textSize = 16.sp.toPx()
                    isAntiAlias = true
                }
                // 计算文本位置（居中显示）
                val textBounds = Rect()
                textPaint.getTextBounds(text, 0, text.length, textBounds)
                val x = (size.width - textBounds.width()) / 2
                val y = (size.height + textBounds.height()) / 2

                canvas.nativeCanvas.drawText(text, x, y, textPaint)
            }
        }
    }

    @SuppressLint("SuspiciousModifierThen")
    fun Modifier.noFontPadding() = this.then(
        layout { measurable, constraints ->
            measurable.measure(constraints).let {
                val bottom = it.height - it[LastBaseline]
                val top = bottom
                var height = it.height - bottom - top
                layout(it.width, height) {
                    it.placeRelative(0, -top)
                }
            }
        }
    )

    @Preview(showBackground = true)
    /**
     * 约束布局使用
     */
    @Composable
    fun ComposeTest1() {

        ConstraintLayout(
            modifier = Modifier
                .background(Color.Cyan)
                .fillMaxWidth()
                .wrapContentHeight()
        ) {
            val (button1, button2, text) = createRefs()
            val b = createEndBarrier(button1, button2)

            Button(
                onClick = {},
                modifier = Modifier.constrainAs(button1) {

                    top.linkTo(parent.top, margin = 16.dp)
                    start.linkTo(parent.start, margin = 16.dp)

                }
            ) {
                Text("按钮1111111")
            }

            Button(
                onClick = {},
                modifier = Modifier.constrainAs(button2) {
                    top.linkTo(button1.bottom)
                    start.linkTo(button1.start)
                }
            ) {
                Text("按钮222222222")
            }
            Text(
                "测试文本",
                modifier = Modifier
                    .background(colorResource(R.color.purple_200))
                    .constrainAs(text) {

                        top.linkTo(button2.bottom)
                        start.linkTo(parent.start)
                        end.linkTo(b)
                        width = Dimension.fillToConstraints
                    },
                textAlign = TextAlign.End
            )
        }
    }


    @Preview

    @OptIn(ExperimentalMaterial3Api::class)
    @Preview(showBackground = true)
    @Composable
    fun ContentV() {
        Scaffold(
            topBar = {
                TopAppBar(
                    title = { Text("Compose测试") },
                    navigationIcon = {
                        AsyncImage(
                            model = "https://bkimg.cdn.bcebos.com/pic/0e2442a7d933c8951f47bfe1db1373f08202006a?x-bce-process=image/format,f_auto/quality,Q_70/resize,m_lfit,limit_1,w_536",
                            contentDescription = null,
                            modifier = Modifier.size(30.dp)
                        )
                    },
                    actions = {
                        Button(onClick = {
                            ToastUtil.showShort("点击了")
                        }) {
                            Text("点击我")
                        }
                    },
                    colors = TopAppBarDefaults.topAppBarColors(
                        containerColor = Color.Magenta,
                        titleContentColor = Color.Yellow,
                        actionIconContentColor = Color.Red,
                        navigationIconContentColor = Color.Blue
                    )

                )
            },
            containerColor = Color.Yellow,
            bottomBar = {
                Row(
                    modifier = Modifier
                        .background(Color.Cyan)
                        .height(50.dp)
                ) {
                    //底部导航栏，4个按钮
                    Text(
                        "首页",
                        modifier = Modifier
                            .height(50.dp)
                            .weight(1f)
                            .wrapContentHeight(align = Alignment.CenterVertically)
                            .clickable {},
                        textAlign = TextAlign.Center
                    )
                    Text(
                        "我的",
                        modifier = Modifier
                            .height(50.dp)
                            .weight(1f)
                            .wrapContentHeight(align = Alignment.CenterVertically)
                            .clickable {},
                        textAlign = TextAlign.Center
                    )
                    Text(
                        "发现",
                        modifier = Modifier
                            .height(50.dp)
                            .weight(1f)
                            .clickable {}
                            .wrapContentHeight(align = Alignment.CenterVertically),
                        textAlign = TextAlign.Center
                    )
                    Text(
                        "更多",
                        modifier = Modifier
                            .height(50.dp)
                            .weight(1f)
                            .background(Color.Green)
                            .clickable {}
                            .wrapContentHeight(Alignment.CenterVertically),

                        textAlign = TextAlign.Center
                    )
                }
            }
        ) {
            TestView(it)

        }
    }


    @Composable
    fun TestView(values: PaddingValues) {
        Column(modifier = Modifier.padding(values)) {
            Box(
                modifier = Modifier
                    .size(100.dp)
                    .clip(RoundedCornerShape(10.dp, 20.dp, 20.dp, 10.dp))
                    .background(Color.Red)
                    .border(
                        2.dp,
                        Color.Blue,
                        shape = RoundedCornerShape(10.dp, 20.dp, 20.dp, 10.dp)
                    )
            ) {

            }
            Row {
                Image(
                    modifier = Modifier
                        .size(80.dp)
                        .clip(CircleShape)
                        .border(width = 0.5.dp, color = colorResource(id = R.color.purple_200)),
                    painter = painterResource(id = R.drawable.ic_launcher),
                    contentDescription = null
                )
                Spacer(modifier = Modifier.weight(1f))
                Button(
                    modifier = Modifier.align(Alignment.CenterVertically),
                    onClick = {
                        startActivity(
                            Intent(
                                this@ComposeTestActivity,
                                ComposeNoteActivity::class.java
                            )
                        )
                    }) {
                    Text(text = "compose学习笔记")
                }
            }


            val list = vm.data.observeAsState(initial = emptyList()).value
            LazyColumn {
                items(items = list, key = { it.id }) { item ->
                    LogUtil.d(TAG, "item绘制 $item")
                    val x = remember { mutableIntStateOf(0) }
                    Text(
                        text = "Hello, Android! ${item.name}  ${x.intValue}",
                        modifier = Modifier
                            .defaultMinSize(minHeight = 50.dp)
                            //.fillParentMaxWidth()//不要用这个，会导致没有变动的item也会重绘的问题，应该用fillMaxWidth()
                            .fillMaxWidth()
                            .clickable {
                                ToastUtil.showShort("click $item")
                                //vm.removeItem(item)
                                x.intValue++
                                vm.changeItem(list.indexOf(item), "new $item")
                            })
                }
            }
        }


    }
}


data class TestListItem(var name: String) {
    val id: Int = name.hashCode()
}

class ComposeTestVm : ViewModel() {
    private val _data = MutableLiveData<List<TestListItem>>()
    val data: LiveData<List<TestListItem>> = _data


    fun initData() {
        val list = mutableListOf<TestListItem>()
        repeat(100) {
            list.add(TestListItem("item $it"))
        }
        _data.value = list
    }

    fun removeItem(item: TestListItem) {
        _data.value = _data.value?.filterNot { it.id == item.id }
    }

    fun changeItem(index: Int, newName: String) {
        _data.value = _data.value?.toMutableList()?.apply { this[index].name = newName }

    }
}